//
//  XUISplitTableView.m
//  etionUI
//
//  Created by WangJian on 14-12-18.
//  Copyright (c) 2014年 GuangZhouXuanWu. All rights reserved.
//

#import "XUISplitTableView.h"
#import "XUISplitView.h"

const float splitTableViewCellHeight = 50.0;
const float splitTableViewTargetArrawSize = 20.0;

@interface XUISplitTableViewTargetArrow : UIView

@end

@implementation XUISplitTableViewTargetArrow

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.backgroundColor = [UIColor clearColor];
        self.layer.opaque = NO;
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextMoveToPoint(context, self.width, 0);
    CGContextAddLineToPoint(context, 0, self.height/2);
    CGContextAddLineToPoint(context, self.width, self.height);
    CGContextAddLineToPoint(context, self.width, 0);
    
    CGContextSetFillColorWithColor(context, [UIColor colorWithWhite:0.97+0.03*(self.width/(splitTableViewTargetArrawSize/2)) alpha:1.0].CGColor);
    CGContextFillPath(context);
}

@end

#pragma mark =========================================

@interface XUISplitTableViewItem : NSObject

@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger targetRow;
@property (nonatomic, strong) XUISplitTableViewTargetArrow *targetArrow;
@property (nonatomic, assign) XUISplitViewContentStatus status;

@end

@implementation XUISplitTableViewItem

- (id)init
{
    if (self = [super init])
    {
        self.contentView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease_mm];
        self.contentView.backgroundColor = [UIColor whiteColor];
        
        self.targetArrow = [[[XUISplitTableViewTargetArrow alloc] initWithFrame:CGRectMake(0, 0, 0, splitTableViewTargetArrawSize)] autorelease_mm];
        [self.contentView addSubview:self.targetArrow];
    }
    return self;
}

-(void)dealloc
{
    [_targetArrow release_mm];
    [_contentView release_mm];
    superdealloc_mm;
}

- (void)setTableView:(UITableView *)tableView
{
    [_tableView removeFromSuperview];
    _tableView = tableView;
    _tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    
    self.contentView.frame = CGRectMake(self.contentView.left, self.contentView.top, tableView.width, tableView.height);
    tableView.frame = self.contentView.bounds;
    [self.contentView addSubview:tableView];
}

@end

#pragma mark =========================================

@interface XUISplitTableView () <XUISplitViewDelegate, UITableViewDataSource, UITableViewDelegate, XUITableViewDelegate>
{
    NSUInteger _currentSelectedViewIndex;
}
@property (nonatomic, strong) XUISplitView *splitView;
@property (nonatomic, strong) NSMutableArray *tableViewItems;

@end

@implementation XUISplitTableView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        
        self.backgroundColor = [UIColor colorWithHex:0xe6e6e6];
        
        self.splitView = [[[XUISplitView alloc] initWithFrame:self.bounds] autorelease_mm];
        self.splitView.delegate = self;
        [self addSubview:self.splitView];
        
        self.tableViewItems = [NSMutableArray array];
    }
    return self;
}

-(void)dealloc
{
    [_splitView release_mm];
    [_tableViewItems release_mm];
    superdealloc_mm;
}

- (NSInteger)tableViewNumber
{
    return self.tableViewItems.count;
}

- (UITableView *)createNewTableView
{
    XUITableView *tableView = [[XUITableView alloc] initWithFrame:CGRectMake(0, 0, self.width-splitLeftViewDisplayWidth, self.height) style:UITableViewStylePlain];
    tableView.separatorExistFollowCell = YES;
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.backgroundColor = [UIColor clearColor];
    tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
#ifdef __IPHONE_8_0
    if([tableView respondsToSelector:@selector(setLayoutMargins:)])
        tableView.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0);
#endif
    
    if([self.delegate respondsToSelector:@selector(registerCellClassForSplitTableView:)])
    {
        NSDictionary *cells = [self.delegate registerCellClassForSplitTableView:self];
        [cells enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop)
        {
            [tableView registerClass:obj forCellReuseIdentifier:key];
        }];
    }
    else
    {
        [tableView registerClass:[XUISplitTableViewCell class] forCellReuseIdentifier:@"cell"];
    }

    return [tableView autorelease_mm];
}

- (void)moveToPrevLevel
{
    if (self.tableViewNumber >= 3)
    {
        [self.splitView setLeftViewIndex:self.tableViewNumber-3 animated:YES];
    }
}

- (void)addTableViewWithPrevTargetRow:(NSInteger)prevTargetRow
{
    UITableView *tableView = [self createNewTableView];
    tableView.tag = self.tableViewItems.count;
    
    XUISplitTableViewItem *item = [[[XUISplitTableViewItem alloc] init] autorelease_mm];
    item.tableView = tableView;
    item.targetRow = prevTargetRow;
    [self.tableViewItems addObject:item];
    [self.splitView addContentView:item.contentView];
    [self updateTargetArrowPositionForIndex:tableView.tag];
    
    if (self.tableViewNumber >= 2)
    {
        [self.splitView moveContentViewAtIndexToLeft:self.tableViewNumber-2 animated:YES];
    }
}

- (void)replaceLastTableViewWithPrevTargetRow:(NSInteger)prevTargetRow
{
    XUISplitTableViewItem *item = self.tableViewItems.lastObject;
    if (self.tableViewItems.count > 1)
    {
        XUISplitTableViewItem *prevItem = self.tableViewItems[self.tableViewItems.count-2];
        [prevItem.tableView deselectRowAtIndexPath:[NSIndexPath indexPathForRow:item.targetRow inSection:0] animated:YES];
    }
    
    [UIView animateWithDuration:splitViewAnimationDuration/2 animations:^{
        item.tableView.left = 40;
        item.tableView.alpha = 0.0;
    } completion:^(BOOL finished) {
        UITableView *tableView = [self createNewTableView];
        tableView.tag = self.tableViewItems.count-1;
        item.tableView = tableView;
        tableView.left = 40;
        tableView.alpha = 0.0;
        item.targetRow = prevTargetRow;
        [UIView animateWithDuration:splitViewAnimationDuration/2 animations:^{
            [self updateTargetArrowPositionForIndex:tableView.tag];
            item.tableView.left = 0;
            item.tableView.alpha = 1.0;
        } completion:^(BOOL finished) {
            
        }];
    }];
}

- (void)deleteLastTableView
{
    if(self.tableViewItems.count > 1)
    {
        [self.splitView deleteLastContentViewWithAnimated:YES];
    }
}

- (void)removeLastTableView
{
    if (self.tableViewItems.count > 1)
    {
        [self.splitView removeLastContentView];
        [self.tableViewItems removeLastObject];
    }
}

- (XUISplitTableViewCell *)cellAtIndex:(NSInteger)index row:(NSInteger)row
{
    XUISplitTableViewItem *item = [self.tableViewItems objectAtIndex:index];
    return (XUISplitTableViewCell *)[item.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0]];
}

- (id)dequeueReusableCellForTableViewAtIndex:(NSInteger)index row:(NSInteger)row
{    
    return [self dequeueReusableCellWithIdentifier:@"cell" forTableViewAtIndex:index row:row];
}

- (id)dequeueReusableCellWithIdentifier:(NSString*)identifier forTableViewAtIndex:(NSInteger)index row:(NSInteger)row
{
    XUISplitTableViewItem *item = [self.tableViewItems objectAtIndex:index];
    return [item.tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:[NSIndexPath indexPathForRow:row inSection:0]];
}

- (void)selectIndex:(NSInteger)index row:(NSInteger)row
{
    _currentSelectedViewIndex = index;
    
    XUISplitTableViewItem *item = [self.tableViewItems objectAtIndex:index];
    [item.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
    [self tableView:item.tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0]];
}

- (NSUInteger)selectedRowAtViewIndex:(NSUInteger)index
{
    XUISplitTableViewItem *item = [self.tableViewItems objectAtIndex:index];
    return [item.tableView indexPathForSelectedRow].row;
}

- (NSUInteger)currentSelectedViewIndex
{
    return _currentSelectedViewIndex;
}

- (void)deselectIndex:(NSInteger)index row:(NSInteger)row
{
    XUISplitTableViewItem *item = [self.tableViewItems objectAtIndex:index];
    [item.tableView deselectRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0] animated:YES];
}

#pragma mark - inner methord

- (void)updateTargetArrowPositionForIndex:(NSInteger)index
{
    if (index == 0)
    {
        return;
    }
    
    XUISplitTableViewItem *item = [self.tableViewItems objectAtIndex:index];
    XUISplitTableViewItem *prevItem = [self.tableViewItems objectAtIndex:index-1];
    
    item.targetArrow.centerY = item.targetRow*splitTableViewCellHeight+splitTableViewCellHeight/2 - prevItem.tableView.contentOffset.y;
}

#pragma mark - splitView delegate

- (BOOL)splitView:(XUISplitView *)splitView contentViewAtIndex:(NSInteger)index statusWillChangeFrom:(XUISplitViewContentStatus)curStatus to:(XUISplitViewContentStatus)newStatus
{
    XUISplitTableViewItem *item = self.tableViewItems[index];
    for (XUISplitTableViewCell *cell in [item.tableView visibleCells])
    {
        [UIView animateWithDuration:splitViewAnimationDuration animations:^
        {
            [cell setStatus:newStatus animated:YES];
        }];
    }
    if (index > 0)
    {
        [UIView animateWithDuration:splitViewAnimationDuration animations:^
        {
            if (newStatus == XUISplitViewContentStatusRight)
            {
                item.targetArrow.frame = CGRectMake(-splitTableViewTargetArrawSize/2, item.targetArrow.top, splitTableViewTargetArrawSize/2, splitTableViewTargetArrawSize);
            }
            else
            {
                item.targetArrow.frame = CGRectMake(0, item.targetArrow.top, 0, splitTableViewTargetArrawSize);
            }
        }];
    }
    
    if (curStatus == XUISplitViewContentStatusLeft && newStatus == XUISplitViewContentStatusRight && index < self.tableViewNumber-1)
    {
        XUISplitTableViewItem *nextItem = self.tableViewItems[index+1];
        [item.tableView deselectRowAtIndexPath:[NSIndexPath indexPathForRow:nextItem.targetRow inSection:0] animated:YES];
    }
    
    return YES;
}

- (void)splitView:(XUISplitView *)splitView contentViewAtIndex:(NSInteger)index statusDidChangeFrom:(XUISplitViewContentStatus)curStatus to:(XUISplitViewContentStatus)newStatus
{
    XUISplitTableViewItem *item = self.tableViewItems[index];
    item.status = newStatus;
    if (curStatus == XUISplitViewContentStatusRight && newStatus == XUISplitViewContentStatusRightHide)
    {
        [self removeLastTableView];
        [self.delegate splitTableView:self didRemoveViewAtIndex:index];
    }
}

#pragma mark - table view

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.delegate splitTableView:self numberOfRowsAtViewIndex:tableView.tag];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return splitTableViewCellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XUISplitTableViewItem *item = self.tableViewItems[tableView.tag];
    XUISplitTableViewCell *cell = [self.delegate splitTableView:self cellAtViewIndex:tableView.tag row:indexPath.row];
    cell.status = item.status;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    _currentSelectedViewIndex = tableView.tag;
    
    return [self.delegate splitTableView:self didClickedCellAtViewIndex:tableView.tag row:indexPath.row];
}

- (NSIndexPath*)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [self.delegate splitTableView:self willClickedCellAtViewIndex:tableView.tag row:indexPath.row];
    if(row < 0)
        return nil;
    return [NSIndexPath indexPathForRow:row inSection:0];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ([scrollView isKindOfClass:[UITableView class]] && scrollView.tag < self.tableViewItems.count-1)
    {
        [self updateTargetArrowPositionForIndex:scrollView.tag+1];
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
#ifdef __IPHONE_8_0
    if([cell respondsToSelector:@selector(setLayoutMargins:)])
        cell.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0);
#endif
}

@end
